<?php
/**
 * Created by PhpStorm.
 * User: bzg
 * Date: 2019/11/27
 * Time: 15:16
 */

namespace App\Extend\SysExtend\Config;

use EasySwoole\Component\Di;

/**
 * 自定义配置操作类
 * Class Config
 * @package App\SysExtend\Config
 */
class Config
{
    // 配置目录
    private $dir = EASYSWOOLE_ROOT . '/App/Config';

    // 所有配置
    private $config = [];

    /**
     * 加载所有配置项,此方法需要注册到easyswoole初始化（initialize）事件中
     */
    public function load()
    {
        $temp = scandir($this->dir);
        //遍历文件夹
        foreach($temp as $v){
            $a = $this->dir . '/' . $v;
            if(is_file($a)){
                $this->config[str_replace('.php','',$v)] = include_once $a;
            }
        }
        // 将自己放入容器
        Di::getInstance()->set('extendConfig',$this);
    }


    /**
     * 获取配置项的值
     * @param string $name 配置项名 点语法
     * @return array|mixed|null
     */
    public function get(string $name = null)
    {
        if($name) {
            // 分解点语法
            $name_array = explode('.',$name);
            // 根据名称一层层的找对应的值
            $current_value = $this->config;
            foreach ($name_array as $v) {
                if(isset($current_value[$v])) {
                    $current_value = $current_value[$v];
                }else{
                    return null;
                }
            }
            return $current_value;
        }
        // 返回所有配置项
        return $this->config;
    }

}